<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

namespace bai\action;

use bai\feature\Paths;
use bai\resource\Document, bai\resource\document\Locale;


class View extends \bai\Action
{
    public const VIEW_INDEX = 'index.html';
    public const VIEW_404 = '404.html';

    public function run()
    {
        $page = $this->mapPage(self::$process->path);
        $doc = Document::setup([
            'path' => $page,
            'params' => $this->find('params')
        ]);
        self::$response->addResource($doc);
        return $this->next();
    }

    protected function mapPage(string $path): string
    {
        $default = null;
        $map = $this->find('map') ?? [];
        foreach ($map as $page => $items) {
            if ($items === '*') {
                $default = $page;
                continue;
            }
            if (!is_array($items)) continue;
            foreach ($items as $item) {
                $params = Paths::mapPath($path, $item);
                if ($params !== null) {
                    $this->runtime['params'] = $params;
                    return $page;
                }
            }
        }
        return $default ?? self::VIEW_404;
    }
}
